using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace B.S.BasicData.Api.Read.Filters
{
    /// <summary>
    /// ①实现授权过滤器接口
    /// ②在过滤方法中查找荷载 payload
    /// ③在荷载中提取过期时间(unix的时间戳),如果为空则赋值为0
    /// ④把过期时间与当前时间比较,如果过期则把请求状态变为401
    /// </summary>
    public class AccessTokenFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var claims = context.HttpContext.User.Claims;
            var exp = 0L;
            long.TryParse(claims.Where(x => x.Type == "exp").FirstOrDefault()?.Value ?? "0", out exp); //取出过期时间,并转为long类型的时间戳
            var current = DateTimeOffset.UtcNow.ToUnixTimeSeconds();//把当前时间转为long类型的 unix时间戳 

            if (exp < current)
            {//过期时间比当前时间小,过期
                context.Result = new UnauthorizedObjectResult("您的访问token已经过期!");//跳转到401
            }
        }
    }
}
